//
//  UIView+category_CCKit.m
//  CCKit
//
//  Created by tucici on 2019/3/18.
//  Copyright © 2019 tucici. All rights reserved.
//

#import "UIView+category_CCKit.h"
#import <objc/runtime.h>
static const CAGradientLayer *gradientLayerStr;
@implementation UIView (category_CCKit)
- (UIView *)findKeyBoard
{
    UIView *keyboardView = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in [windows reverseObjectEnumerator])
    {
        keyboardView = [self findKeyBoardInView:window];
        if (keyboardView)
        {
            return keyboardView;
        }
    }
    return nil;
}
- (UIView *)findKeyBoardInView:(UIView *)view
{
    for (UIView *subView in [view subviews])
    {
        if (strstr(object_getClassName(subView), "UIKeyboard"))
        {
            return subView;
        }
        else
        {
            UIView *tempView = [self findKeyBoardInView:subView];
            if (tempView)
            {
                return tempView;
            }
        }
    }
    return nil;
}

- (UIViewController *)superViewController
{
    UIResponder *next = [self nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next != nil);
    return nil;
}

/// UIView绘制成image,使用该方法不会模糊，根据屏幕密度计算
- (UIImage *)drawImage
{
    UIImage *imageRet = [[UIImage alloc]init];
    //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度);
    UIGraphicsBeginImageContextWithOptions(self.frame.size, YES, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageRet;
}
#pragma mark == set
- (void)setGradientLayer:(CAGradientLayer *)gradientLayer
{
    objc_setAssociatedObject(self, &gradientLayerStr, gradientLayer, OBJC_ASSOCIATION_RETAIN);
}
#pragma mark == get
- (CAGradientLayer *)gradientLayer
{
    return objc_getAssociatedObject(self, &gradientLayerStr);
}
@end
